package hotciv.variants;

import hotciv.common.CityImpl;
import hotciv.common.Utility;
import hotciv.common.WorldMap;
import hotciv.framework.City;
import hotciv.framework.CityResourceStrategy;
import hotciv.framework.GameConstants;
import hotciv.framework.Position;
import hotciv.framework.Tile;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;

public class EtaCityResource implements CityResourceStrategy {

	@Override
	public void calculateCityResources(City city, WorldMap world) {
		if (city.getSize()<1) return;
		Position cityPosition = world.getCityPosition(city);
		int food = 1;
		int production = 1;
		
		if (city.getSize()>1) { //Calculate from adjacent tiles
			
			Iterator<Position> neighbors = Utility.get8NeighborhoodIterator(cityPosition);
			ArrayList<Tile> neighborTiles = new ArrayList<Tile>();
			while (neighbors.hasNext()) {
				neighborTiles.add(world.getTileAt(neighbors.next()));
			}
			Collections.sort(neighborTiles, new TileComparator(city.getWorkforceFocus()) );
			//System.out.println("Sorted tiles: "+neighborTiles);
			for (int i= 0;i<city.getSize()-1;i++) {
				food += Utility.getFoodValue(neighborTiles.get(i));
				production += Utility.getProductionValue(neighborTiles.get(i));
			}
		}
		
		CityImpl cityImpl = (CityImpl) city;
		cityImpl.setFoodStock(cityImpl.getFoodStock() + food);
		cityImpl.setProductionStock(cityImpl.getProductionStock() + production);
		
	}
	
	

}

class TileComparator implements Comparator<Tile> {
	private String focus;
	
	public TileComparator (String focus) {
		this.focus = focus;
	}
	    
    public int compare(Tile a, Tile b) {
        int foodComp = Utility.getFoodValue(b) - Utility.getFoodValue(a);
        int prodComp = Utility.getProductionValue(b) - Utility.getProductionValue(a);
    	if (focus.equals(GameConstants.foodFocus)) {
    		if (foodComp==0) return prodComp;
    		else return foodComp;
    	} else {
    		if (prodComp==0) return foodComp;
    		else return prodComp;
    	}
    }
    
    
}
